define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/agency_remit/index' + location.search,
                    add_url: 'pt/agency_remit/add',
                    edit_url: 'pt/agency_remit/edit',
                    del_url: 'pt/agency_remit/del',
                    multi_url: 'pt/agency_remit/multi',
                    import_url: 'pt/agency_remit/import',
                    table: 'pt_agency_remit',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {field: 'agency_name', title: __('Agency_name'), operate: 'LIKE'},
                        {field: 'amount', title: __('Amount'), operate:false},
                        {field: 'remit_type_text', title: __('Remit_type') ,searchList:{'1':'银行转账','2':'微信转账','3':'支付宝转账','4':'现金'}, formatter:function(v,r,index){ 
                            
                            return `<span class="label label-primary">${v}</span>`;
                        }},
                        {field: 'remit_time', title: __('Remit_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'remit_no', title: __('Remit_no'), operate: 'LIKE'},
                        {field: 'remarks', title: __('Remarks'), operate:false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'remit_orders', title: "资金组成", operate: false, formatter: function (value, row, index) {
                            try {
                                // 兼容多种键名与类型：数组/JSON字符串
                                var source = (row && (row.remit_orders || row.remitOrders)) ?? value;
                                if (!source) return '-';
                                var list = Array.isArray(source) ? source : (typeof source === 'string' ? JSON.parse(source) : []);
                                if (!Array.isArray(list) || list.length === 0) return '-';

                                // 简单转义
                                var escape = function (s) {
                                    return String(s || '').replace(/[&<>"]/g, function (c) {
                                        return {'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;'}[c] || c;
                                    });
                                };

                                var orderTypeNames = {
                                    '1': '职称',
                                    '2': '继续教育',
                                    '3': '专利', 
                                    '4': '软著',
                                    '5': '科研',
                                    '6': '论文',
                                    '7': '学历'
                                };

                                var htmlParts = [];
                                for (var i = 0; i < list.length; i++) {
                                    var item = list[i] || {};
                                    var orderType = item.order_type || '';
                                    var orderTypeName = orderTypeNames[orderType] || '未知类型';
                                    var userName = item.user_name || '';
                                    var amount = item.amount || '';
                                    
                                    htmlParts.push("<div style='margin-bottom: 3px; padding: 2px 5px; background: #f5f5f5; border-radius: 3px; display: inline-block; margin-right: 5px;'>");
                                    htmlParts.push("<span style='color:#884ffb; font-weight: bold;'>" + escape(orderTypeName) + "</span> ");
                                    htmlParts.push("<span style='color:#884ffb;'>" + escape(userName) + "</span> ");
                                    if (amount) {
                                        htmlParts.push("<span style='color:#884ffb;'>¥" + escape(amount) + "</span>");
                                    }
                                    htmlParts.push("</div>");
                                }
                                return htmlParts.join('');
                            } catch (e) {
                                return '-';
                            }
                        }},
                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
      
        },
        edit: function () {
            Controller.api.bindevent();

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                Controller.api.bindFieldlistEvents();
                Controller.api.bindOrderSelectEvents();
            },
            bindFieldlistEvents: function () {
                // 绑定fieldlist事件，自动重新排列序号
                $(document).on('click', '.btn-append', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                $(document).on('click', '.btn-remove', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
            },
            
            // 重新排序序列号
            reorderSequence: function() {
                // 这里可以添加重新排序的逻辑，如果需要的话
                // 目前暂时留空，因为fieldlist组件会自动处理
            },
            
            // 绑定订单选择事件
            bindOrderSelectEvents: function() {
                $(document).on('click', '.btn-select-order', function() {
                    var $row = $(this).closest('.form-inline');
                    var orderType = $row.find('select[name*="[order_type]"]').val();
                    
                    if (!orderType) {
                        Toastr.error('请先选择订单类型');
                        return;
                    }
                    
                    Controller.api.showOrderSelectDialog(orderType, $row);
                });
            },
            
            // 显示订单选择弹窗
            showOrderSelectDialog: function(orderType, $row) {
                var orderTypeNames = {
                    '1': '职称',
                    '2': '继续教育',
                    '3': '专利', 
                    '4': '软著',
                    '5': '科研',
                    '6': '论文',
                    '7': '学历',
                    
                };
                
                var orderTypeName = orderTypeNames[orderType] || '订单';
                
                var content = `
                    <div class="order-select-dialog" style="padding: 15px;">
                        <div class="form-group" style="margin-bottom: 15px;">
                            <label style="margin-right: 10px;">搜索条件：</label>
                            <input type="text" id="order-keyword" class="form-control" placeholder="请输入用户姓名搜索" style="width: 200px; display: inline-block; margin-right: 10px;">
                            <button type="button" id="search-orders" class="btn btn-primary">搜索</button>
                        </div>
                        <div class="table-responsive" style="margin-bottom: 15px;">
                            <table class="table table-striped table-hover table-bordered">
                                <thead class="thead-light">
                                    <tr>
                                        <th style="width: 80px;">选择</th>
                                        <th style="width: 120px;">用户姓名</th>
                                        <th style="width: 200px;">订单编号</th>
                                    </tr>
                                </thead>
                                <tbody id="order-list-tbody">
                                    <tr><td colspan="3" class="text-center">加载中...</td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div id="order-pagination" class="text-center"></div>
                    </div>
                `;
                
                Layer.open({
                    type: 1,
                    title: '选择' + orderTypeName + '订单',
                    area: ['600px', '450px'],
                    content: content,
                    success: function(layero, index) {
                        Controller.api.loadOrderList(orderType, 1, '', $row);
                        
                        // 绑定搜索事件
                        $('#search-orders').on('click', function() {
                            var keyword = $('#order-keyword').val();
                            Controller.api.loadOrderList(orderType, 1, keyword, $row);
                        });
                        
                        // 绑定回车搜索
                        $('#order-keyword').on('keypress', function(e) {
                            if (e.which === 13) {
                                var keyword = $(this).val();
                                Controller.api.loadOrderList(orderType, 1, keyword, $row);
                            }
                        });
                    }
                });
            },
            
            // 加载订单列表
            loadOrderList: function(orderType, page, keyword, $row) {
                $.post(Fast.api.fixurl('pt/agency_remit/getOrderList'), {
                    order_type: orderType,
                    page: page,
                    limit: 10,
                    keyword: keyword
                }, function(ret) {
                    if (ret.code === 1) {
                        var html = '';
                        if (ret.data.list.length > 0) {
                            $.each(ret.data.list, function(index, item) {
                                html += '<tr>';
                                html += '<td><button type="button" class="btn btn-sm btn-primary btn-select-item" data-id="' + item.id + '" data-name="' + item.user_name + '">选择</button></td>';
                                html += '<td>' + item.user_name + '</td>';
                                html += '<td>' + (item.order_no || '') + '</td>';
                                html += '</tr>';
                            });
                        } else {
                            html = '<tr><td colspan="3" class="text-center">暂无数据</td></tr>';
                        }
                        $('#order-list-tbody').html(html);
                        
                        // 绑定选择事件
                        $('.btn-select-item').on('click', function() {
                            var orderId = $(this).data('id');
                            var userName = $(this).data('name');
                            
                            // 回填数据
                            $row.find('input[name*="[order_id]"]').val(orderId);
                            $row.find('input[name*="[user_name]"]').val(userName);
                            
                            // 关闭弹窗
                            Layer.closeAll();
                            
                            Toastr.success('订单选择成功');
                        });
                        
                        // 生成分页
                        if (ret.data.total > 10) {
                            Controller.api.generatePagination(ret.data.total, page, orderType, keyword, $row);
                        } else {
                            $('#order-pagination').html('');
                        }
                    } else {
                        Toastr.error(ret.msg);
                    }
                });
            },
            
            // 生成分页
            generatePagination: function(total, currentPage, orderType, keyword, $row) {
                var totalPages = Math.ceil(total / 10);
                var html = '<nav><ul class="pagination pagination-sm">';
                
                // 上一页
                if (currentPage > 1) {
                    html += '<li><a href="javascript:;" onclick="Controller.api.loadOrderList(\'' + orderType + '\', ' + (currentPage - 1) + ', \'' + keyword + '\', $(\'.form-inline\').eq(0))">上一页</a></li>';
                }
                
                // 页码
                for (var i = 1; i <= totalPages; i++) {
                    if (i === currentPage) {
                        html += '<li class="active"><span>' + i + '</span></li>';
                    } else {
                        html += '<li><a href="javascript:;" onclick="Controller.api.loadOrderList(\'' + orderType + '\', ' + i + ', \'' + keyword + '\', $(\'.form-inline\').eq(0))">' + i + '</a></li>';
                    }
                }
                
                // 下一页
                if (currentPage < totalPages) {
                    html += '<li><a href="javascript:;" onclick="Controller.api.loadOrderList(\'' + orderType + '\', ' + (currentPage + 1) + ', \'' + keyword + '\', $(\'.form-inline\').eq(0))">下一页</a></li>';
                }
                
                html += '</ul></nav>';
                $('#order-pagination').html(html);
            }
        }
    };
    
    return Controller;
});
